package cn.kow.kmall.controller.system;

import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.controller.BaseController;
import cn.kow.kmall.core.exception.ServiceException;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.system.entity.SysNotice;
import cn.kow.kmall.system.service.SysNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-10-29 17:04
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/notice")
public class SysNoticeController extends BaseController {

    @Autowired
    private SysNoticeService noticeService;

    /**
     * 新增公告
     * @param notice  公告
     * @return 结果
     */
    @PostMapping(value = "/add")
    public KmallResult add(@Validated @RequestBody SysNotice notice) {
        notice.setCreateBy(currentUser().getUsername());
        noticeService.save(notice);
        return KmallResult.success();
    }

    /**
     * 删除公告
     * @param id    公告ID
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public KmallResult remove(@PathVariable Long id) {
        noticeService.remove(id);
        return KmallResult.success();
    }

    /**
     * 修改公告
     * @param notice  公告
     * @return 结果
     */
    @PostMapping(value = "/edit")
    public KmallResult edit(@Validated @RequestBody SysNotice notice) {
        notice.setUpdateBy(currentUser().getUsername());
        noticeService.update(notice);
        return KmallResult.success();
    }

    /**
     * 根据公告ID获取详细信息
     * @param id    岗位ID
     * @return 结果
     */
    @GetMapping(value = "/{id}")
    public KmallResult getInfo(@PathVariable Long id) {
        SysNotice config = noticeService.getById(id);
        if (null == config) {
            throw new ServiceException(KmallResultEnum.DAO_NOT_FOUND);
        }
        return KmallResult.success(config);
    }

    /**
     * 获取公告列表
     */
    @GetMapping("/list")
    public KmallResult list(@RequestParam(required = false) String title,
                            @RequestParam(required = false) String type,
                            @RequestParam(required = false) Short status,
                            @PageableDefault(sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable) {
        Page<SysNotice> page = noticeService.listByPage(title, type, status, pageable);
        return KmallResult.success().put("rows", page.getContent())
                .put("total", page.getTotalElements());
    }
}

